package com.letoken.platform.repo.web3.util;

import cn.hutool.core.util.StrUtil;
import com.letoken.platform.pub.res.web3.ResultTransaction;
import com.letoken.platform.pub.util.HttpClientUtil;
import com.letoken.platform.repo.admin.manager.AppChainNodeManager;
import com.letoken.platform.repo.admin.redis.AppChainNodeRedis;
import com.letoken.platform.repo.wallet.po.Web3ChainProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.web3j.abi.FunctionEncoder;
import org.web3j.abi.TypeDecoder;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.crypto.*;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.DefaultBlockParameterNumber;
import org.web3j.protocol.core.methods.response.*;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.Transfer;
import org.web3j.utils.Numeric;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;

/**
 * @author letokenlabs
 * @date 2022/11/16$
 */
@Slf4j
@Component
public class EvmUtil {

    @Autowired
    AppChainNodeManager appChainNodeManager;

    public static final BigDecimal ETH_DECIMALS = new BigDecimal(1_000_000_000_000_000_000L);

    /**
     * 校验EVM地址
     *
     * @param input
     * @return
     */
    public static boolean checkAddressChecksum(String input) {
        if (StrUtil.isEmpty(input) || !input.startsWith("0x"))
            return false;
        return isValidAddress(input);
    }

    public static boolean isValidAddress(String input) {
        String cleanInput = Numeric.cleanHexPrefix(input);

        try {
            Numeric.toBigIntNoPrefix(cleanInput);
        } catch (NumberFormatException e) {
            return false;
        }

        return cleanInput.length() == 40;
    }

    /**
     * 获取Web3j对象（支持代理）
     *
     * @return
     */
    public static Web3j getWeb3j(Web3ChainProvider provider) {

        String url = AppChainNodeRedis.me().getQuickNode(provider.getNetwork());
        if (StringUtils.isEmpty(url)) {
            url = provider.getEndpoint();
        }
        if (provider.getProxy()) {
            return Web3j.build(new HttpService(url, HttpClientUtil.getProxyClient(provider.getProxyUrl())));
        } else {
            return Web3j.build(new HttpService(url));
        }
    }

    public static Web3j getNextWeb3j(String netType) {
        String url = AppChainNodeRedis.me().getNodeByRoundRobin(netType, 6);
        return Web3j.build(new HttpService(url));
    }

    public static Web3j getQuickWeb3j(String netType) {
        String url = AppChainNodeRedis.me().getQuickNode(netType);
        return Web3j.build(new HttpService(url));
    }

    /**
     * 获取最新区块高度
     *
     * @param web3j
     * @return
     */
    public static long blockHeight(Web3j web3j) {

        try {
            EthBlockNumber blockNumber = web3j.ethBlockNumber().sendAsync().get();
            return blockNumber.getBlockNumber().longValue();

        } catch (Exception e) {
            log.error(String.format("EvmUtil > blockHeight error!"), e);
        }
        return Long.valueOf(0);
    }

    /**
     * 获取GasPrice
     *
     * @param web3j
     * @return wei
     */
    public static BigInteger getGasPrice(Web3j web3j) {
        try {
            EthGasPrice ethGasPrice = web3j.ethGasPrice().sendAsync().get();
            return ethGasPrice.getGasPrice();
        } catch (Exception e) {
            log.error(String.format("EvmUtil > getGasPrice error!"), e);
        }
        return null;
    }

    /**
     * 获取nonce
     *
     * @param web3j
     * @param address
     * @return
     */
    public static BigInteger getNonce(Web3j web3j, String address) {
        try {
            EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(address, DefaultBlockParameterName.PENDING).sendAsync().get();
            if (ethGetTransactionCount == null) {
                log.error("GetNonceError:" + address);
                return null;
            }
            return ethGetTransactionCount.getTransactionCount();
        } catch (Throwable t) {
            log.error("GetNonceError:" + address);
        }
        return null;
    }


    /**
     * 根据交易hash获取交易状态
     *
     * @param txhash
     * @param web3j
     * @return
     */
    public static String getTxReceiptstatus(String txhash, Web3j web3j) {

        try {
            EthGetTransactionReceipt receipt = web3j.ethGetTransactionReceipt(txhash).sendAsync().get();
            return receipt.getResult().getStatus().replace("0x", "");
        } catch (Exception e) {
            log.error(String.format("EvmUtil > getTxReceiptstatus error! txhash:%s", txhash), e);
        }
        return null;
    }

    /**
     * 获取单个地址的ETH余额
     *
     * @param address 钱包地址
     * @param web3j
     * @return wei
     */
    public static String getBalance(String address, Web3j web3j) {

        try {
            EthBlockNumber blockNumber = web3j.ethBlockNumber().sendAsync().get();
            EthGetBalance balance = web3j.ethGetBalance(address, new DefaultBlockParameterNumber(blockNumber.getBlockNumber())).sendAsync().get();
            return balance.getBalance().toString();
        } catch (Exception e) {
            log.error(String.format("EvmUtil > getBalance error! address:%s", address), e);
        }
        return null;
    }


    /**
     * 获取钱包代币余额（erc20)
     *
     * @param tokenAddress 代币合约地址
     * @param address      用户钱包地址
     * @return wei
     */
    public static String getTokenBalance(String tokenAddress, String address, Web3j web3j) {

        try {
            final String DATA_PREFIX = "0x70a08231000000000000000000000000";
            String value = web3j.ethCall(org.web3j.protocol.core.methods.request.Transaction.createEthCallTransaction(address,
                    tokenAddress, DATA_PREFIX + address.substring(2)), DefaultBlockParameterName.PENDING).sendAsync().get().getValue();
            if (!StrUtil.isEmptyIfStr(value)) {
                return new BigInteger(value.substring(2), 16).toString();
            }
        } catch (Throwable t) {
            log.error(String.format("EvmUtil getTokenBalance error! token:%s address:%s", tokenAddress, address), t);
        }
        return null;
    }

    /**
     * 发送原生代币
     *
     * @param privateKey 钱包秘钥
     * @param toAddress  收款钱包地址
     * @param value      转账数量(wei)
     * @return txHash
     * @throws Exception
     */
    public static String transfer(Web3j web3j, String privateKey, String toAddress, BigDecimal value) throws Exception {

        if (web3j != null) {
            return sendEth(web3j, privateKey, toAddress, value);
        }
        return null;
    }

    public static String transferToken(Web3j web3j, String contractAddress, String privateKey, String toAddress, BigDecimal value, BigInteger gasPrice, BigInteger gasLimit) {

        if (web3j != null) {
            String from = getAddressByPrivateKey(privateKey);
            log.info(String.format("Start:SendErc20 from:%s to:%s amount:%s erc20:%s", from, toAddress, value.toString(), contractAddress));
            try {
                //加载转账所需的凭证，用私钥
                Credentials credentials = Credentials.create(privateKey);
                //获取nonce，交易笔数
                BigInteger nonce = getNonce(web3j, from);
                if (nonce == null) {
                    log.error(String.format("END:GetNonceError from:%s to:%s amount:%s erc20:%s", from, toAddress, value.toString(), contractAddress));
                    return null;
                }

                if (gasPrice.equals(0)) {
                    log.error(String.format("END:GetGasPriceError from:%s to:%s amount:%s erc20:%s", from, toAddress, value.toString(), contractAddress));
                    return null;
                }

                //ERC20代币合约方法
                Function function = new Function(
                        "transfer",
                        Arrays.asList(new Address(toAddress), new Uint256(value.toBigInteger())),
                        Collections.singletonList(new TypeReference<Type>() {
                        }));

                //创建RawTransaction交易对象
                String encodedFunction = FunctionEncoder.encode(function);
                RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit,
                        contractAddress, encodedFunction);

                //签名Transaction
                byte[] signMessage = TransactionEncoder.signMessage(rawTransaction, web3j.ethChainId().send().getChainId().longValue(), credentials);
                String hexValue = Numeric.toHexString(signMessage);
                //发送交易
                EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
                String hash = ethSendTransaction.getTransactionHash();
                if (hash != null) {
                    return hash;
                }
                log.error(String.format("END:HashIsNull from:%s to:%s amount:%s erc20:%s >> %s",
                        from, toAddress, value.toString(), contractAddress, ethSendTransaction.getError().getMessage()));
            } catch (Throwable t) {
                log.error(String.format("发送ERC20失败 from=%s to=%s erc20=%s amount=%s >> %s",
                        from, toAddress, contractAddress, value.toString(), t.getMessage()), t);
            }
        }
        return null;
    }

    /**
     * 根据私钥获取地址
     *
     * @param privateKey
     * @return
     */
    public static String getAddressByPrivateKey(String privateKey) {
        ECKeyPair ecKeyPair = ECKeyPair.create(new BigInteger(privateKey, 16));
        return "0x" + Keys.getAddress(ecKeyPair).toLowerCase();
    }

    /**
     * 转换成最小单位 Wei
     *
     * @param ethAmount
     * @return
     */
    public static BigInteger toWei(BigDecimal ethAmount) {
        return ethAmount.multiply(ETH_DECIMALS).toBigInteger();
    }

    /**
     * 转换成最小单位 Wei
     *
     * @param ethAmount
     * @return
     */
    public static BigDecimal toWei2(BigDecimal ethAmount) {
        return ethAmount.multiply(ETH_DECIMALS);
    }

    /**
     * wei to eth
     *
     * @param wei
     * @return
     */
    public static BigDecimal toEth(BigInteger wei) {
        return new BigDecimal(wei).divide(ETH_DECIMALS, 18, RoundingMode.DOWN);
    }

    public static BigDecimal toEthScale(BigInteger wei, int scale) {
        return new BigDecimal(wei).divide(ETH_DECIMALS, scale, RoundingMode.DOWN);
    }

    /**
     * 发送以太坊
     *
     * @param web3j
     * @param privateKey 发送者私钥
     * @param to         收款地址
     * @param value      wei为单位的数量
     * @param gasPrice   gas-price
     * @param gasLimit   gas-limit
     * @return
     */
    public static String sendEth(Web3j web3j, String privateKey, String to, BigInteger value, BigInteger gasPrice, BigInteger gasLimit) {
        String from = getAddressByPrivateKey(privateKey);
        try {
            //加载转账所需的凭证，用私钥
            Credentials credentials = Credentials.create(privateKey);
            //获取nonce，交易笔数
            BigInteger nonce = getNonce(web3j, from);
            //创建RawTransaction交易对象
            RawTransaction rawTransaction = RawTransaction.createEtherTransaction(nonce, gasPrice, gasLimit, to, value);
            //签名Transaction，这里要对交易做签名
            byte[] signMessage = TransactionEncoder.signMessage(rawTransaction, web3j.ethChainId().send().getChainId().longValue(), credentials);
            String hexValue = Numeric.toHexString(signMessage);
            //发送交易
            EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();

            log.debug(String.format("sendEth >> from:%s to:%s amount:%s gasPrice:%s gasLimit:%s", from, to, value, gasPrice, gasLimit));

            return ethSendTransaction.getTransactionHash();
        } catch (Throwable t) {
            log.error(String.format("发送ETH失败 from:%s to:%s amount-eth:%s >> %s", from, to, toEth(value).toString(), t.getMessage()));
        }
        return null;
    }

    /**
     * 发送以太坊
     *
     * @param web3j
     * @param privateKey 发送者私钥
     * @param to         收款地址
     * @param value      wei为单位的数量
     * @return
     */
    public static String sendEth(Web3j web3j, String privateKey, String to, BigDecimal value) {
        return sendEth(web3j, privateKey, to, value.toBigInteger(), getGasPrice(web3j), Transfer.GAS_LIMIT);
    }

    /**
     * 根据hash获取交易信息
     *
     * @param web3j
     * @param hash
     * @return
     */
    public static EthTransaction getTransaction(Web3j web3j, String hash) {
        try {
            EthTransaction tx = web3j.ethGetTransactionByHash(hash).send();
            return tx;
        } catch (Throwable t) {
            log.error("GetTransactionError:" + hash, t);
        }
        return null;
    }

    public static TransactionReceipt getTransactionReceipt(Web3j web3j, String hash) {
        try {
            EthGetTransactionReceipt receipt = web3j.ethGetTransactionReceipt(hash).send();
            return receipt.getResult();
        } catch (Throwable t) {
            log.error("GetTransactionError:" + hash, t);
        }
        return null;
    }

    public static List<Log> getErc20TransferLogs(Web3j web3j, String hash) {
        try {
            EthGetTransactionReceipt receipt = web3j.ethGetTransactionReceipt(hash).send();
            return receipt.getResult().getLogs();
        } catch (Throwable t) {
            log.error("getErc20TransferValue:" + hash, t);
        }
        return null;
    }

    public static BigInteger getErc20TransferValue(Web3j web3j, String hash) {
        try {
            EthGetTransactionReceipt receipt = web3j.ethGetTransactionReceipt(hash).send();
            String data = receipt.getResult().getLogs().get(0).getData();
            return TypeDecoder.decodeNumeric(data, Uint256.class).getValue();
        } catch (Throwable t) {
            log.error("getErc20TransferValue:" + hash, t);
        }
        return null;
    }

    public static List<String> getBlockTokenTranscationHashs(Web3j web3j, String tokenAddress, String blockNumber) {
        List<String> txs = new ArrayList<>();
        try {
            EthBlock block = web3j.ethGetBlockByNumber(new DefaultBlockParameterNumber(Long.parseLong(blockNumber)), true).send();
            if (block != null) {
                if (block.getBlock() != null) {
                    List<EthBlock.TransactionResult> transactions = block.getBlock().getTransactions();
                    if (transactions != null && !transactions.isEmpty()) {
                        for (EthBlock.TransactionResult tx : transactions) {

                            EthBlock.TransactionObject obj = (EthBlock.TransactionObject) tx.get();
                            if (obj != null) {
                                if (!StringUtils.isEmpty(tokenAddress) && !tokenAddress.equalsIgnoreCase(obj.getTo())) {
                                    continue;
                                }
                                txs.add(obj.getHash());
                            }
                        }
                    }
                    return txs;
                }
            }
        } catch (Throwable t) {
            log.error(String.format("getBlockTokenTranscationHashs error! block:%s", blockNumber), t);
        }
        return null;
    }

    public static List<ResultTransaction> getBlockTokenTransactions(Web3j web3j, String tokenAddress, String blockNumber) {
        List<ResultTransaction> txs = new ArrayList<>();
        try {
            List<String> hashs = getBlockTokenTranscationHashs(web3j, tokenAddress, blockNumber);
            if (hashs != null) {
                if (!hashs.isEmpty()) {
                    for (String hash : hashs) {
                        ResultTransaction item = getTransactionByHash(web3j, hash);
                        if (item != null) {
                            txs.add(item);
                        }
                    }
                }
                return txs;
            }
        } catch (Throwable t) {
            log.error(String.format("getBlockTokenTranscations error! block:%s", blockNumber), t);
        }
        return null;
    }

    public static ResultTransaction getTransactionByHash(Web3j web3j, String hash) {
        try {
            Optional<TransactionReceipt> receipt = web3j.ethGetTransactionReceipt(hash).send().getTransactionReceipt();
            if (receipt != null && receipt.isPresent()) {
                TransactionReceipt tx = receipt.get();

                ResultTransaction item = new ResultTransaction();
                item.setBlockNumber(tx.getBlockNumber().toString());
                item.setBlockHash(tx.getBlockHash());
                item.setHash(tx.getTransactionHash());
                item.setAddress(tx.getContractAddress());
                item.setFromAddress(tx.getFrom());
                item.setToAddress(tx.getTo());
                item.setReceiptStatus(Numeric.cleanHexPrefix(tx.getStatus()));

                if (tx.getLogs() != null && !tx.getLogs().isEmpty()) {
                    Log log = tx.getLogs().get(0);
                    if (log != null && log.getTopics().get(2) != null) {

                        if(!StringUtils.isEmpty(log.getAddress())) {
                            item.setAddress(log.getAddress());
                        }

                        if (!StringUtils.isEmpty(log.getData())) {
                            item.setValue(TypeDecoder.decodeNumeric(log.getData(), Uint256.class).getValue().toString());
                        }

                        String topic1 = log.getTopics().get(1);
                        if (topic1 != null && !StringUtils.isEmpty(topic1)) {
                            item.setFromAddress(TypeDecoder.decodeAddress(topic1).toString());
                        }

                        String topic2 = log.getTopics().get(2);
                        if (topic2 != null && !StringUtils.isEmpty(topic2)) {
                            item.setReciever(TypeDecoder.decodeAddress(topic2).toString());
                        }
                    }
                }

                return item;
            }
        } catch (Throwable t) {
            log.error(String.format("getTransactionByHash error! hash:%s", hash), t);
        }
        return null;
    }
}
